package icasue.net.socket.exception;

import icasue.net.base.annotations.Nullable;
import icasue.net.protocol.http.common.Const;
import com.alibaba.fastjson.JSON;
import icasue.net.protocol.carfun.common.BizCode;
import icasue.net.protocol.carfun.common.CommandResponse;

/**
 * @Author: Qiao Hang
 * @CreateDate: 2021/3/19 下午2:49
 * @UpdateDate:
 * @Description:
 */
public class ProcessorBrokeException extends RuntimeException {
    private static final String TIPS = "Protocol processor has broken, perhaps Command or Driver un support, or protocol data isValid.";
    private static final String protocolTemp = new StringBuffer()
            .append("@PROCESSOR_BROKE %s\r\n")
            .append("*Length: %s\r\n")
            .append("*CharSet: UTF-8\r\n")
            .append("DataType: JSON\r\n")
            .append("\r\n")
            .append("%s")
            .append("\r\t")
            .toString();
    /*出现Processor中断异常后，使用默认BizCode.ERROR的提示信息，
    还是使用默认Processor中断的提示信息，待定，目前使用BizCode.ERROR的默认失败信息*/
    public String message = TIPS;
    public CommandResponse res;
    public ProcessorBrokeException(@Nullable CommandResponse res) {
        super(TIPS);
        this.res = res;
    }

    public byte[] getProtocol(){
        if(res == null){
            res = CommandResponse.error(BizCode.ERROR);
        }
        String resJSON = JSON.toJSONString(res);
        return String.format(
                    protocolTemp,
                    res.getCode(),
                    resJSON.getBytes(Const.UTF_8).length,
                    resJSON
                ).getBytes(Const.UTF_8);
    }
}
